package com.example.gokuplayalong.service.fragments.users.receive;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.UiContext;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.MainActivity;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.baiduapi.BaiduApi;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.custom.textwatcher.RegExUtil;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragments.users.others.UserMainChat;
import com.example.gokuplayalong.service.fragments.users.profile.UserMainProfileMerchantInfo;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserMainReceiveUserInfo#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class UserMainReceiveUserInfo extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    View rootView;
    private ImageView mUserMainReceiveUserinfoIv;
    private ImageView mUserMainReceiveUserinfoMessage;
    private ImageView mUserMainReceiveUserinfoHeadshot;
    private TextView mUserMainReceiveUserinfoMerchantName;
    private TextView mUserMainReceiveUserinfoMerchantNameChange;
    private TextView mUserMainReceiveUserinfoMerchantServicesShow;

    private TextView mUserMainReceiveUserinfoMerchantScore;
    private TextView mUserMainReceiveUserinfoMerchantId;
    private TextView mUserMainReceiveUserinfoMerchantAddress;
    private TextView mUserMainReceiveUserinfoMerchantIntroduce;
    private TextView mUserMainReceiveUserinfoMerchantManifesto;
    private LinearLayout mUserMainReceiveUserinfoMerchantSkills;
    private LinearLayout mUserMainReceiveUserinfoMerchantGameProwess;
    private LinearLayout mUserMainReceiveUserinfoMerchantGameShow;
    private Button mUserMainReceiveUserinfoMerchantFind;
    JSONArray skillsList = new JSONArray();

    Beans bean = new Beans();
    JSONObject merchantInfo = new JSONObject();
    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    try {
                        Bundle bundle = msg.getData();
                        bean.setJsonObject(JSON.parseObject(bundle.getString("bean")));

                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
            }
        }
    };


    public UserMainReceiveUserInfo() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserMainReceiveUserInfo.
     */
    // TODO: Rename and change types and number of parameters
    public static UserMainReceiveUserInfo newInstance(String param1, String param2) {
        UserMainReceiveUserInfo fragment = new UserMainReceiveUserInfo();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_user_main_receive_user_info, container, false);
        initView();
        return rootView;
    }

    private void initView() {

        mUserMainReceiveUserinfoIv = rootView.findViewById(R.id.user_main_receive_userinfo_iv);
        mUserMainReceiveUserinfoMessage = rootView.findViewById(R.id.user_main_receive_userinfo_message);
        mUserMainReceiveUserinfoHeadshot = rootView.findViewById(R.id.user_main_receive_userinfo_headshot);
        mUserMainReceiveUserinfoMerchantName = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_name);
        mUserMainReceiveUserinfoMerchantNameChange = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_name_change);
        mUserMainReceiveUserinfoMerchantManifesto = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_manifesto);
        mUserMainReceiveUserinfoMerchantScore = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_score);
        mUserMainReceiveUserinfoMerchantId = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_id);
        mUserMainReceiveUserinfoMerchantAddress = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_address);
        mUserMainReceiveUserinfoMerchantIntroduce = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_introduce);
        mUserMainReceiveUserinfoMerchantSkills = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_skills);
        mUserMainReceiveUserinfoMerchantGameProwess = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_game_prowess);
        mUserMainReceiveUserinfoMerchantGameShow = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_game_show);
        mUserMainReceiveUserinfoMerchantFind = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_find);
        mUserMainReceiveUserinfoMerchantServicesShow = rootView.findViewById(R.id.user_main_receive_userinfo_merchant_services_show);


        mUserMainReceiveUserinfoMerchantFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    Message message = new Message();
                    message.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putString("bean", bean.getJsonObject().toJSONString());
                    message.setData(bundle);

                    UserMainReceiveUserInfoPlaceOrder userMainReceiveUserInfoPlaceOrder = (UserMainReceiveUserInfoPlaceOrder) AppParams.getInstance().sysfragmentmanager.findFragmentByTag("UserMainReceiveUserInfoPlaceOrder");
                    if (userMainReceiveUserInfoPlaceOrder != null) {
                        userMainReceiveUserInfoPlaceOrder.handler.sendMessage(message);
                        userMainReceiveUserInfoPlaceOrder.handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                SysManagerFragments.switchOnSysFragment("UserMainReceiveUserInfoPlaceOrder");

                            }
                        }, 200);
                    }
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });

        mUserMainReceiveUserinfoIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchBackOnSysFragment();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });

        mUserMainReceiveUserinfoMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;

                    Message message = new Message();
                    message.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putString("bean", bean.getJsonObject().toJSONString());
                    message.setData(bundle);

                    UserMainChat userMainChat = (UserMainChat) AppParams.getInstance().sysfragmentmanager.findFragmentByTag("UserMainChat");
                    if (userMainChat != null) {
                        userMainChat.handler.sendMessage(message);
                        userMainChat.handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    SysManagerFragments.switchOnSysFragment("UserMainChat");
                                } catch (Throwable e) {

                                }
                            }
                        }, 200);
                    }


                    SysManagerFragments.switchOnSysFragment("UserMainChat");
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
        }
    }

    private void initChanged() {
        try {
            String filename = bean.getJsonObject()
                    .getString("phone") + "_merchant_headshot_upload.png";
            Picasso.with(MainActivity.getInstance())
                    .load(AppParams.getInstance().uploadMediaLocationServer + "/" + filename)
//                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .networkPolicy(NetworkPolicy.NO_CACHE)
                    .into(mUserMainReceiveUserinfoHeadshot);

            if (mUserMainReceiveUserinfoMerchantSkills != null && mUserMainReceiveUserinfoMerchantSkills.getChildCount() > 0)
                mUserMainReceiveUserinfoMerchantSkills.removeAllViews();
            if (mUserMainReceiveUserinfoMerchantGameProwess != null && mUserMainReceiveUserinfoMerchantGameProwess.getChildCount() > 0)
                mUserMainReceiveUserinfoMerchantGameProwess.removeAllViews();
            if (mUserMainReceiveUserinfoMerchantGameShow != null && mUserMainReceiveUserinfoMerchantGameShow.getChildCount() > 0)
                mUserMainReceiveUserinfoMerchantGameShow.removeAllViews();

            UIRefresh();
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }


    void UIRefresh() {
        try {

            merchantInfo = JSON.parseObject(bean.getJsonObject().getString("merchantInfo"));
            skillsList = JSON.parseArray(bean.getJsonObject().getString("skillsList"));

            if (merchantInfo != null) {
                mUserMainReceiveUserinfoMerchantId.setText(String.format("ID:%s", merchantInfo.getString("merchantid")));
                JSONObject data = JSON.parseObject(merchantInfo.getString("data"));
                if (data != null) {
                    if (!StringUtils.isEmpty(data.getString("merchantName"))) {
                        mUserMainReceiveUserinfoMerchantName.setText(data.getString("merchantName"));
                    }
                    else {
                        if (Objects.equals(data.getString("bodyType"), "企业") || Objects.equals(data.getString("bodyType"), "个体工商户")) {
                            mUserMainReceiveUserinfoMerchantName.setText(data.getString("companiesMerchantAbbreviation"));
                        }
                        else if (Objects.equals(data.getString("bodyType"), "个人")) {
                            mUserMainReceiveUserinfoMerchantName.setText(data.getString("individualMerchantAbbreviation"));
                        }
                    }
                    if (!StringUtils.isEmpty(data.getDoubleValue("merchantScore") + "")) {
                        mUserMainReceiveUserinfoMerchantScore.setText(String.format("%s分", data.getDoubleValue("merchantScore")));
                    }
                    else {
                        mUserMainReceiveUserinfoMerchantScore.setText("0.0分");
                    }

                    if (!StringUtils.isEmpty(data.getString("merchantIntroduce"))) {
                        mUserMainReceiveUserinfoMerchantIntroduce.setText(data.getString("merchantIntroduce"));
                    }

                    if (!StringUtils.isEmpty(data.getString("merchantManifesto"))) {
                        mUserMainReceiveUserinfoMerchantManifesto.setText(data.getString("merchantManifesto"));
                    }
                    try {
                        JSONObject servicetype = JSON.parseObject(merchantInfo.getString("servicetype"));
                        if (servicetype != null) {
                            StringBuilder serviceType = new StringBuilder();
                            Iterator<String> iterator = servicetype.keySet().iterator();
                            while (iterator.hasNext()) {
                                String key = (String) iterator.next();
                                serviceType.append(key)
                                        .append(":")
                                        .append(servicetype.getString(key))
                                        .append("元/小时\n");
                            }
                            mUserMainReceiveUserinfoMerchantServicesShow.setText(serviceType.toString());
                        }
                        else {
                            mUserMainReceiveUserinfoMerchantServicesShow.setText("");
                        }

                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }

                    mUserMainReceiveUserinfoMerchantSkills.removeAllViews();
                    mUserMainReceiveUserinfoMerchantGameShow.removeAllViews();


                    List<TextView> skillsGameType = new ArrayList<>();

                    for (int i = 0; i < skillsList.size(); i++) {

                        TextView textView = new TextView(rootView.getContext());
                        textView.setId(("UserMainReceiveUserInfo_textview_merchant_skills_" + i + "_rand").hashCode());
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                        lp.setMargins(20, 20, 20, 20);
                        textView.setLayoutParams(lp);

                        textView.setTextSize(25);
                        textView.setTextColor(Color.BLACK);
                        textView.setText(skillsList.getJSONObject(i).getString("gametype"));

                        textView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                try {


                                    mUserMainReceiveUserinfoMerchantGameProwess.removeAllViews();

                                    for (int i = 0; i < skillsGameType.size(); i++) {
                                        skillsGameType.get(i).setTextColor(Color.BLACK);
                                    }

                                    for (int i = 0; i < skillsGameType.size(); i++) {
                                        if (skillsGameType.get(i).getId() == view.getId()) {

                                            //显示标签
                                            skillsGameType.get(i).setTextColor(Color.BLUE);
                                            Iterator<String> sIterator = JSON.parseObject(skillsList.getJSONObject(i)
                                                    .getString("data")).keySet().iterator();

                                            while (sIterator.hasNext()) {
                                                LinearLayout childView = (LinearLayout) LayoutInflater.from(requireContext())
                                                        .inflate(R.layout.fragment_user_main_receive_user_info_template, mUserMainReceiveUserinfoMerchantGameProwess, false);

                                                String key = sIterator.next();
                                                if (!Objects.equals(key, "imageViewsName")) {
                                                    TextView textView1 = childView.findViewById(R.id.user_main_receive_user_info_template_label);
                                                    textView1.setText(key + ":");
                                                    textView1 = childView.findViewById(R.id.user_main_receive_user_info_template_desc);
                                                    textView1.setText(JSON.parseObject(skillsList.getJSONObject(i)
                                                            .getString("data")).getString(key));
                                                    mUserMainReceiveUserinfoMerchantGameProwess.addView(childView);

                                                }


//                                            显示图片
                                                mUserMainReceiveUserinfoMerchantGameShow.removeAllViews();

                                                List<String> imageViewsName = new ArrayList<>(Arrays.asList(JSON.parseObject(skillsList.getJSONObject(i)
                                                                .getString("data"))
                                                        .getString("imageViewsName")
                                                        .split(",")));

                                                for (int j = 0; j < imageViewsName.size(); j++) {
                                                    ImageView imageView = new ImageView(rootView.getContext());

                                                    imageView.setId(("UserMainReceiveUserInfo_imageview_merchant_skills_" + j + "_rand").hashCode());

                                                    Picasso.with(MainActivity.getInstance())
                                                            .load(AppParams.getInstance().uploadMediaLocationServer + "/" + imageViewsName.get(j))
                                                            .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                                                            .networkPolicy(NetworkPolicy.NO_CACHE)
                                                            .into(imageView);

                                                    mUserMainReceiveUserinfoMerchantGameShow.addView(imageView);
                                                }
                                            }
                                        }
                                    }


                                } catch (Throwable e) {
                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                }
                            }
                        });
                        skillsGameType.add(textView);
                        mUserMainReceiveUserinfoMerchantSkills.addView(textView);
                    }

                    if (!skillsGameType.isEmpty()) skillsGameType.get(0).performClick();


                }
            }


        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }
}